package com.bprogram.utils;

import com.bprogram.config.RabbitMqConfig;
import com.rabbitmq.client.*;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class RabbitMqUtil {

    /**
     * 将信息发送给mq，指明交换机和备份交换机名称
     *
     * @param msg       存对应用户注册码的key
     * @param queueName 队列名称，传来的是注册用户的邮箱
     * @param type      使用用用途
     * @param ttl       消息过期时间
     * @throws IOException
     * @throws TimeoutException
     */
    public static void registerMq(String msg, String queueName, String type, long ttl) throws IOException, TimeoutException {
        Channel channel = RabbitMqConfig.getChannel();
        //声明交换机
        channel.exchangeDeclare(type + "Exchange", BuiltinExchangeType.DIRECT, true);
        channel.exchangeDeclare(type + "BackupsExchange", BuiltinExchangeType.DIRECT, true);
        channel.exchangeDeclare(type + "DeadExchange", BuiltinExchangeType.DIRECT, true);
//        声明队列
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl", ttl);  // 设置消息失效,map的key一定不能有空格，否则失效
        arguments.put("x-dead-letter-exchange", type + "DeadExchange"); //设置死信交换机和路由
        arguments.put("x-dead-letter-routing-key", type + "Dead"); //设置死信交换机的路由key
        channel.queueDeclare(queueName, false, false, true, arguments);
        channel.queueDeclare(queueName + "Backups", false, false, true, arguments);
        channel.queueDeclare(queueName + "Dead", false, false, false, null);
        //绑定队列和交换机
        channel.queueBind(queueName, type + "Exchange", type);
        channel.queueBind(queueName + "Backups", type + "BackupsExchange", type + "Backups");
        channel.queueBind(queueName + "Dead", type + "DeadExchange", type + "Dead");
        //发布消息
        channel.basicPublish(type + "Exchange", type, null, msg.getBytes());
        channel.basicPublish(type + "BackupsExchange", type + "Backups", null, msg.getBytes());
        System.out.println("send success!" + msg);
    }

    /**
     * 消费者消费信息
     *
     * @param queueName
     * @param deliverCallback
     * @param cancelCallback
     * @throws IOException
     * @throws TimeoutException
     */
    public static void consumer(String queueName, DeliverCallback deliverCallback, CancelCallback cancelCallback) throws IOException, TimeoutException {
        Channel channel = RabbitMqConfig.getChannel();
        channel.basicConsume(queueName, true, deliverCallback, cancelCallback);
        channel.close();
    }
}
